<?php namespace App\Http\Controllers\admin\project;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Input;
use App\Models\ProjectTypes;
use App\Models\EnergyTypes;
use App\Models\Projects;
use App\Models\ProjectDevice;
use App\Models\ProjectTech;
use App\Models\ProjectTechnologies;
use App\Models\InvestmentType;
use App\Models\MainBody;
use App\Models\Techs;
use App\Models\Area;
use App\Models\Domains;
use App\Models\ProjectBidding;
use App\Models\Devices;
use App\Models\Technologies;
use App;
use DB;
use Session;
use App\Models\ProjectDomain;
use App\Models\ProjectMainBody;
use Validator;
use App\Models\Users;
use App\Models\ProjectProgress;
use Redirect;





class ProjectController extends Controller {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	// 项目列表页
	public function index()
	{
		//
		if(Session::has('admin')){
			return view("admin.project.index")->withIsProject(true);
	    }else{
	    	return Redirect::to('admin/dologin');
	    }
	}

	// 项目编辑页
	public function editProject()
	{
		$pid = (int)Input::get("pid");
		$model = Projects::with(['investmentType', 'mainBody', 'projectTech', 'projectDomain', 'projectDomain.domain', 'projectDomain.domain.parent'])->where("id", $pid);

		if($model->count()){
			$data = $model->get()[0]->toArray();
			$domains = Domains::where("parent_id", 0)->get()->toArray();
		}else{
			return App::abort(404);
		}

		// return $data;
		return view("admin.project.edit_project", ['data' => $data, 'domains' => $domains])->withIsProject(true);
	}

	public function addProject()
	{
		return view("admin.project.add_project")->withIsProject(true);
	}

	// 项目详情
	public function detailProject()
	{
		return view("admin.project.detail_project")->withIsProject(true);
	}

	// 项目列表接口
	public function projectList()
	{
		$current = (int)Input::get("current");
		$rowCount = (int)Input::get("rowCount");
		$sort = Input::get("sort")["id"];
		$sort = $sort ? $sort : "desc";

		$keywords = Input::get('searchPhrase');
		$model = new Projects;
		$count = $model->get()->count();
		$model = Projects::with(['province', 'city', 'area', 'projectDomain', 'investmentType', 'projectDomain.domain', 'projectDomain.domain.parent', 'energyType',]);

		 if($keywords){

			$projects = $model->where("name", "like", "%".$keywords."%")->orWhere("description", "like", "%".$keywords."%")->skip(($current - 1)*$rowCount)->take($rowCount)->get()->toArray();
		}else{
			$project = $model->skip(($current - 1)*$rowCount)->take($rowCount)->get()->toArray();
        }

		return array(
			"current" => $current,
			"rowCount" => $rowCount,
			"rows" => $project,
			"total" => $count
			);
    }

	public function getDetail()
	{

		$pid = Input::get("pid");
		$model = Projects::with(['investmentType', 'mainBody.mainBody', 'projectTech.tech', 'projectDomain.domain', 'biddings', 'technologies', 'devices', 'province', 'city', 'area', 'projectDomain'])->where("id", $pid);
		if($model->count()){
			$data = $model->get()[0]->toArray();
			$project_device = ProjectDevice::with(["device"])->where("project_id", $pid)->get()->toArray();
			$project_tech = ProjectTechnologies::with(["technology"])->where("project_id", $pid)->get()->toArray();
			$data["use_device"] = $project_device;
			$data["use_tech"] = $project_tech;
			return $this->json(["data" => $data]);
		}else{
			return;
		}

	}

     public function saveProject()
	{
		$rule = [];
		$msg = [];
		$validator = Validator::make(Input::all(), $rule, $msg);
		if($validator->passes()){
            
			$uid = $this->getUid();
			$data = Input::all();
			$imgArr = Input::only('image');
			$this->moveImages($imgArr, env("PROJECT_DIR"));
			$data['uid'] = $uid;
			$project = Projects::create($data);
			$techs = Input::get("techs");
			$domains = Input::get("domains");
			foreach ($techs as $tech)
			{
				ProjectTech::create(["cate_id" => $tech, "project_id" => $project->id]);
			}
			foreach ($domains as $domain)
			{
				ProjectDomain::create(["cate_id" => $domain, "project_id" => $project->id]);
			}
			$project_device = Input::get("device");
			$project_tech = Input::get("useTech");
			foreach ($project_device as $value) {
				ProjectDevice::create(["project_id" => $project->id, "device_id" => $value]);
			}
			foreach ($project_tech as $value) {
				ProjectTechnologies::create(["project_id" => $project->id, "tech_id" => $value]);
			}
			$mainBody = Input::get("main_body");
			ProjectMainBody::create(["mb_id" => $mainBody, "project_id" => $project->id]);

			return $this->json([]);

		}else{
			$errors = $validator->messages();
			return self::error('', $errors->first());
		}
	}

	public function updateProject()
	{
		$rule = [];
		$msg = [];
		$validator = Validator::make(Input::all(), $rule, $msg);
		if($validator->passes()){
			$pid = (int)Input::get("pid", 0);
			$model = Projects::where("id", $pid);
			if($model->count()){
				$data = Input::except('pid', 'domains', 'techs', 'main_body', 'bidding_id', 'device', 'useTech');
				$imgArr = Input::only('image');
				$this->moveImages($imgArr, env("PROJECT_DIR"), $uid);
				$model->update($data);
				$tech_model = ProjectTech::where("project_id", $pid);
				$tech_model->delete();
				$domain_model = ProjectDomain::where("project_id", $pid);
				$domain_model->delete();
				$techs = Input::get("techs");
				$domains = Input::get("domains");
				foreach ($techs as $tech)
				{
					ProjectTech::create(["cate_id" => $tech, "project_id" => $pid]);
				}
				foreach ($domains as $domain)
				{
					ProjectDomain::create(["cate_id" => $domain, "project_id" => $pid]);
				}
				$mainBody = Input::get("main_body");
				$body_model = ProjectMainBody::where("project_id", $pid);
				$body_model->update(["mb_id" => $mainBody]);
				$bidding_id = (int)Input::get("bidding_id");
				if($bidding_id)
				{
					ProjectBidding::where("project_id", $pid)->update(["is_chosen"=> 0]);
					ProjectBidding::where("id", $bidding_id)->update(["is_chosen" => 1]);
				}
				$project_device = ProjectDevice::where("project_id", $pid)->delete();
				$project_tech = ProjectTechnologies::where("project_id", $pid)->delete();

				$project_device = Input::get("device");
				$project_tech = Input::get("useTech");
				foreach ($project_device as $value) {
					ProjectDevice::create(["project_id" => $pid, "device_id" => $value]);
				}
				foreach ($project_tech as $value) {
					ProjectTechnologies::create(["project_id" => $pid, "tech_id" => $value]);
				}

				return $this->json([]);
			}else{
				return;
			}
		}else{
			$errors = $validator->messages();
			return self::error('', $errors->first());
		}
	}

	public function getUser()
	{
		$users = Users::whereIn("role_id", [2,3,6,7])->where("validate_state", 2)->get();
		foreach ($users as $key => $user) {
			switch ($user['role_id']) {
				case env("ENERGY"):
					$user->load("poweruser")->toArray();
					$user["userData"] = $user["poweruser"];
					unset($user["poweruser"]);
					break;
				case env("SAVER"):
					$user->load("energysaver")->toArray();
					$user["userData"] = $user["energysaver"];
					unset($user["energysaver"]);
					break;
				case env("ASSOCIATION"):
					$user->load("association")->toArray();
					$user["userData"] = $user["association"];
					unset($user["association"]);
					break;
				case env("GOVERNMENT"):
					$user->load("government")->toArray();
					$user["userData"] = $user["government"];
					unset($user["government"]);
					break;
				default:
					break;
			}
		}
		return $this->json(["data"=> $users]);
	}

	public function audit()
	{
		$pid = Input::get("pid");
		$state = Input::get("state");
		$model = Projects::where("id", $pid);
		if($model->count())
		{
			$model->update(["verify_state" => $state]);
			return $this->json([]);
		}
	}


	public function addProgress()
	{
		$pid = Input::get("project_id");
		$data = Input::all();
		ProjectProgress::create($data);

		$data = ProjectProgress::where("project_id", $pid)->get()->toArray();
		return $this->json(["data" => $data]);
	}

	public function getProgress()
	{
		$pid = Input::get("pid");
		$model = ProjectProgress::where("project_id", $pid);
		if($model->count()){
			$data = $model->get()->toArray();
			return $this->json(["data" => $data]);
		}else{
			return;
		}

	}

	public function updateProgress()
	{
		$prg_id = Input::get("prg_id");
		$pid = Input::get("project_id");
		$model = ProjectProgress::where("id", $prg_id);
		if($model->count()){
			$data = Input::only("progress_time", "content");
			$model->update($data);
			$model = ProjectProgress::where("project_id", $pid);
			if($model->count()){
				$data = $model->get()->toArray();
				return $this->json(["data" => $data]);
			}
		}

	}

	public function deleteProgress()
	{
		$prg_id = Input::get("prg_id");
		$pid = Input::get("project_id");
		$model = ProjectProgress::where("id", $prg_id);
		if($model->count()){
			$model->delete();
			$data = ProjectProgress::where("project_id", $pid)->get()->toArray();
			return $this->json(["data" => $data]);
		}
	}


	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

}
